#include <iostream>
#include <unistd.h>
#include <string>
#include <cerrno>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "error.h"

#define backlog 32

using std::cout;
using std::endl;
using std::string;

class Sock
{
public:
    Sock()
    {
        listen_sock_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_sock_ < 0)
        {
            logMessage(Fatal, "creat socket error, code:%d, string:%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        cout << "creat socket success" << endl;
    }

    void Bind(const uint16_t &port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(listen_sock_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(Fatal, "bind socket error, code: %d, error string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }
    void Listen()
    {
        if (listen(listen_sock_, backlog) < 0)
        {
            logMessage(Fatal, "listen error, code: %d, error string: %s", errno, strerror(errno));
            exit(EXIT_FAILURE);
        }
    }
    int Accept(string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in temp;
        memset(&temp, 0, sizeof(temp));
        socklen_t len = sizeof(temp);
        int sock = accept(listen_sock_, (struct sockaddr *)&temp, &len);
        if (sock < 0)
            logMessage(Warning, "accept error, code: %d, error string: %s", errno, strerror(errno));
        else
        {
            *clientip = inet_ntoa(temp.sin_addr);
            *clientport = ntohs(temp.sin_port);
        }
        return sock;
    }
    int Connect(const string &serverip, const uint16_t &serverport)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        socklen_t len = sizeof(server);
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        server.sin_addr.s_addr = INADDR_ANY;
        return connect(listen_sock_, (struct sockaddr *)&server, len);
    }
    int Fd()
    {
        return listen_sock_;
    }

private:
    int listen_sock_;
};